package practise.alogrithm.hundredInterviewQuestions.Utils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by richard on 6/1/14.
 */
public class TreeBuilder {
    static int value=1;
    public static TreeNode buildTree(){
        TreeNode treeNode = new TreeNode();
        treeNode.setValue(7);
        return buildTree(treeNode,3);

    }

    public static void main(String[] args){
        TreeNode treeNode = createTreeByArrayInWidth(new int[]{1,2,3,4,5,6,7,8});
        printTreeWithLevel(treeNode);
    }

    public static TreeNode buildTree(TreeNode treeNode , int level){
        treeNode.setValue(value++);
        if(level==0){

            return treeNode;
        }
        treeNode.setLeft(buildTree(new TreeNode(),level-1));
        treeNode.setRight(buildTree(new TreeNode(),level-1));
        return treeNode;
    }

    public static TreeNode createTreeByArrayInWidth(int[] arrays){
        List<TreeNode> queue = new LinkedList<>();
        TreeNode treeNode = null;
        for(int i : arrays){
           TreeNode newNode = new TreeNode();
            newNode.setValue(i);
            queue.add(newNode);
            if(queue.size()==1){

                treeNode = newNode;
            }
            else{
                TreeNode top = queue.get(0);
                if(top.getLeft()==null){
                    top.setLeft(newNode);
                }
                else{
                    top = queue.remove(0);
                    top.setRight(newNode);
                }
            }
        }

        return treeNode;

    }

    public static void printTreeWithLevel(TreeNode node){
        List<TreeNode> queue = new ArrayList<>();

        int level = 1;
        queue.add(node);
        while(!queue.isEmpty()){

            int size = queue.size();
            System.out.println("Level:"+level);
            for(int i=0; i < size;i++){
                TreeNode currentNode = queue.remove(0);
                System.out.print("["+currentNode.getValue()+"]");
                if(currentNode.getLeft()!=null){
                    queue.add(currentNode.getLeft());
                }
                if(currentNode.getRight()!=null){
                    queue.add(currentNode.getRight());
                }
            }
            level++;
            System.out.println();
        }
    }

    public static void printTree(TreeNode head){
        int level = getTreeLevel(head);
        int printlevel = level*2-1;
        int currentLevel = 1;
        int currentPosition =0;

    }

    public static int getTreeLevel(TreeNode head){
        if(head.getLeft()==null&& head.getRight()==null){
            return 1;
        }
        if(head==null){
            return 0;
        }
        return 1+Math.max(getTreeLevel(head.getLeft()),getTreeLevel(head.getRight()));

    }





}
